package myserver.core;

import myserver.api.TestApi;

import java.io.InputStream;

/**
 * 根据请求类型和URI找到对应的控制器，将请求交给控制器处理
 */
public class ServiceDispatcher {

    /**
     * 转发处理请求
     * @param request
     * @param response
     */
    public void dispatcher(Request request, Response response) {
        execController(request, response);
    }

    /**
     * 根据请求类型及URI等请求信息，找到并执行对应的控制器方法后返回
     * 此处直接返回一个控制器，模拟查找和执行控制器方法的过程
     * @param request
     * @param response
     * @return
     */
    private void execController(Request request, Response response) {
    	
    	//TODO 自己扩展 更多控制器
    	// 动态请求-->动态控制器
    	if(request.getUri().contains("api"))dynamicController(request, response);
    	// 静态请求-->静态控制器
    	else staticController(request, response);
    }

    /**
     * 静态控制器：查找和执行静态文件并返回结果
     * @param request
     * @param response
     */
    private void staticController(Request request, Response response) {
    	
    	response.writeStaticResource(request.getUri());
    }
    
    /**
     * 动态控制器：模拟查找和执行API方法并返回结果
     * @param request
     * @param response
     * @return
     */
    private void dynamicController(Request request, Response response) {
        String text = "";
        String uri = request.getUri();
        System.out.println(uri);
        String[] params=request.getParams();
        String headers=request.getHeaders();
        String raws=request.getRaws();
        InputStream input=request.getInput();
        int index=request.getIndex();
        String [] uriArray = uri.split("\\/");
        if(uriArray.length != 3) {
            text = "请求路径没有找到相关匹配服务. ";
        }
        else if("api".equalsIgnoreCase(uriArray[1])) {
            TestApi testApi = new TestApi();
            testApi.setRequest(request);
            testApi.setResponse(response);
            System.out.println(uriArray[2].substring(0,6));
            if("api1".equalsIgnoreCase(uriArray[2])) {
                    testApi.api1();
            } else if("api2".equalsIgnoreCase(uriArray[2])) {
            	testApi.api2();
            }else if("qsaram".equalsIgnoreCase(uriArray[2].substring(0,6))){
                testApi.api3(params);
            }else if("headerparam".equalsIgnoreCase(uriArray[2])){
                testApi.api4(headers);
            }else if("formbodyparam".equalsIgnoreCase(uriArray[2])){
                testApi.api3(params);
            }else if("rawbodyparam".equalsIgnoreCase(uriArray[2])) {
                testApi.api6(raws);
            } else if("binarybodyparam".equalsIgnoreCase(uriArray[2])){
                testApi.api5(input,index);
            }

            else {
                text = "请求路径没有找到相关匹配服务. ";
            }
        }
        else {
            text = "请求路径没有找到相关匹配服务. ";
        }
        if(!text.isEmpty()) {
        	String rtn="{\"code\":400,\"msg\":\""+text+"\",\"data\":null}";        	
        	// 输出控制器返回结果
            response.writeJson(rtn);
        }
    }

}